package com.devworks.facebook;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.code.facebookapi.FacebookJsonRestClient;

/**
 * Servlet implementation class RestaurantSearch
 */
public class RestaurantSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RestaurantSearch() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String apiKey = getServletConfig().getInitParameter("API_KEY");
		String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
		HttpSession session = request.getSession();
		String sessionKey = (String) session
				.getAttribute("restSearchAppSession");
		String authToken = request.getParameter("auth_token");

		FacebookJsonRestClient client = null;

		if (sessionKey != null) {
			client = new FacebookJsonRestClient(apiKey,
					secretKey,
					sessionKey);

		} else if (authToken != null) {
			client = new FacebookJsonRestClient(apiKey, secretKey);
			client.setIsDesktop(false);
			try {
				sessionKey = client.auth_getSession(authToken);
				session.setAttribute("restSearchAppSession", sessionKey);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			response.sendRedirect("http://www.facebook.com/login.php?api_key=" + apiKey);
			return;
		}
		request.getRequestDispatcher("RestaurantSearch.jsp").forward(request,
				response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
